package com.zhugang.week13.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @program algorithms
 * @description: pathSum
 * @author: chanzhugang
 * @create: 2022/10/24 20:47
 */
public class PathSum {

    /**
     * 剑指offer 34 二叉树中和为某一值的路径
     * https://leetcode.cn/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/
     *
     * @param root
     * @param target
     * @return
     */
    private List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int target) {
        if (root == null) {
            return result;
        }
        // 深度优先搜索
        dfs(root, target, new ArrayList<Integer>(), 0);
        return result;
    }

    private void dfs(TreeNode root, int target, List<Integer> path, int pathSum) {
        path.add(root.val);
        pathSum += root.val;
        if (root.left == null && root.right == null) {
            // 到了叶子节点
            if (pathSum == target) {
                // 得到一组解
                List<Integer> temp = new ArrayList<>();
                temp.addAll(path);
                result.add(temp);
            }
            // 回退一个节点
            path.remove(path.size() - 1);
            return;
        }
        if (root.left != null) {
            dfs(root.left, target, path, pathSum);
        }
        if (root.right != null) {
            dfs(root.right, target, path, pathSum);
        }
        // 有进有出
        path.remove(path.size() - 1);
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}